const app = getApp();
Page({
  data: {
    polyline: [],
    longitude: 116.397428,
    latitude: 39.90923,
    includePoints: [],
    markers: [],
    userMarker: null, // 新增：用户当前位置marker
    showInfoModal: true, // 控制弹窗显示
    editable: true, // 是否可编辑
    showNavModal: false, // 新增：导航选择弹窗
    gpxInfo: {
      filename: '',        // upload接口返回
      displayName: '',     // upload接口返回
      fileSize: '',        // upload接口返回
      distance: '',        // gpx解析
      startTime: '',       // gpx解析
      endTime: '',         // gpx解析
      startLat: '',        // gpx解析
      startLng: '',        // gpx解析
      endLat: '',          // gpx解析
      endLng: '',          // gpx解析
      remark: ''           // 用户可填写
    },
    images: [],
    imageGroups: [],
    defaultDate: '',
  },
  onLoad(options) {
    // 1. 从路由参数获取filename、display_name、file_size、edit
    const filename = options.filename || '';
    const displayName = options.display_name || '';
    const fileSize = options.file_size || '';
    // 修正：如果没有edit参数，默认editable为true
    let editable = true;
    if (options.hasOwnProperty('edit')) {
      editable = options.edit !== '0';
    }
    this.setData({ editable });
    if (!filename) return;

    // 2. 拉取gpx内容并解析
    wx.request({
      url: `${app.globalData.baseUrl}/api/gpx/download/${encodeURIComponent(filename)}`,
      method: 'GET',
      responseType: 'text',
      success: res => {
        const gpxStr = res.data;
        // 解析轨迹点
        const points = parseGpxPoints(gpxStr);
        // 解析路线名
        const roadName = parseGpxRoadName(gpxStr);
        // 解析距离
        const distance = parseGpxDistance(gpxStr);
        // 解析当前时间为预出发
        const now = new Date();
        const pad = n => n < 10 ? '0' + n : n;
        const today = `${now.getFullYear()}-${pad(now.getMonth()+1)}-${pad(now.getDate())}`;
        this.setData({ defaultDate: today });
        const startTime = `${now.getFullYear()}-${pad(now.getMonth()+1)}-${pad(now.getDate())} ${pad(now.getHours())}:${pad(now.getMinutes())}`;
        // 新增：解析起点终点经纬度
        let startLat = '', startLng = '', endLat = '', endLng = '';
        if (points.length > 0) {
          startLat = points[0].latitude;
          startLng = points[0].longitude;
          endLat = points[points.length - 1].latitude;
          endLng = points[points.length - 1].longitude;
        }
        this.setData({
          polyline: points.length ? [{ points, color: '#FF0000DD', width: 4 }] : [],
          longitude: points.length ? points[0].longitude : 116.397428,
          latitude: points.length ? points[0].latitude : 39.90923,
          includePoints: points,
          markers: points.length ? [
            { id: 0, latitude: points[0].latitude, longitude: points[0].longitude, title: '起点', width: 28, height: 28, color: '#07c160', callout: { content: '起点', color: '#fff', bgColor: '#07c160', padding: 4, borderRadius: 8, display: 'ALWAYS' } },
            { id: 1, latitude: points[points.length-1].latitude, longitude: points[points.length-1].longitude, title: '终点', width: 28, height: 28, color: '#FFD600', callout: { content: '终点', color: '#fff', bgColor: '#FFD600', padding: 4, borderRadius: 8, display: 'ALWAYS' } }
          ] : [],
          showInfoModal: true,
          gpxInfo: {
            filename,
            displayName,
            fileSize,
            roadName,
            distance: distance, // 距离在gpxview页面解析
            startTime,
            endTime: '', // 结束时间在gpxview页面解析
            startLat,    // 新增
            startLng,    // 新增
            endLat,      // 新增
            endLng,      // 新增
            remark: ''
          },
          editable
        });
      }
    });
  },
  onReady() {
    this.mapCtx = wx.createMapContext('map', this);
  },
  // 新增：导航按钮点击
  onNavBtnTap() {
    this.setData({ showNavModal: true });
  },
  // 新增：关闭导航弹窗
  closeNavModal() {
    this.setData({ showNavModal: false });
  },
  // 新增：选择实时定位导航
  chooseRealtimeNav() {
    this.setData({ showNavModal: false });
    // 开始实时定位
    wx.startLocationUpdate({
      success: () => {
        wx.onLocationChange((res) => {
          // 更新用户当前位置 marker
          const userMarker = {
            id: 99,
            latitude: res.latitude,
            longitude: res.longitude,
            iconPath: '/images/default.jpg', // 可自定义用户图标
            width: 32,
            height: 32,
            title: '我',
            callout: {
              content: '我',
              color: '#fff',
              bgColor: '#007aff',
              padding: 4,
              borderRadius: 8,
              display: 'ALWAYS'
            }
          };
          // 合并markers
          let markers = this.data.markers.filter(m => m.id !== 99);
          markers.push(userMarker);
          this.setData({
            userMarker,
            markers,
            longitude: res.longitude,
            latitude: res.latitude
          });
        });
      },
      fail: () => {
        wx.showToast({ title: '定位失败', icon: 'none' });
      }
    });
  },
  // 新增：选择原生导航
  chooseNativeNav() {
    this.setData({ showNavModal: false });
    // 跳转到终点
    const { endLat, endLng, displayName } = this.data.gpxInfo;
    if (endLat && endLng) {
      wx.openLocation({
        latitude: Number(endLat),
        longitude: Number(endLng),
        name: displayName || '终点',
        scale: 16
      });
    } else {
      wx.showToast({ title: '无终点信息', icon: 'none' });
    }
  },
  onInputInfo(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({ [`gpxInfo.${field}`]: e.detail.value });
  },
  onPickStartTime(e) {
    this.setData({ 'gpxInfo.startTime': e.detail.value });
  },
  onPickDate(e) {
    this.setData({ 'gpxInfo.date': e.detail.value });
  },
  onPickTime(e) {
    this.setData({ 'gpxInfo.time': e.detail.value });
  },
  getFullStartTime() {
    const { date, time } = this.data.gpxInfo;
    return date && time ? `${date} ${time}` : '';
  },
  // 分组图片，每组2张，滑动宫格
  groupImages(images) {
    const imageGroups = [];
    for (let i = 0; i < images.length; i += 2) {
      imageGroups.push([
        images[i],
        images[i + 1] ? images[i + 1] : null
      ].filter(Boolean));
    }
    // 编辑模式下，布局加号
    if (this.data.editable) {
      if (images.length === 0) {
        this.setData({ images: [], imageGroups: [] });
        return;
      }
      if (images.length % 2 === 0) {
        imageGroups.push([]);
      }
      this.setData({ images, imageGroups });
      return;
    }
    this.setData({ images, imageGroups });
  },
  // 选择图片并上传
  chooseImage() {
    wx.chooseImage({
      count: 9 - this.data.images.length,
      success: res => {
        res.tempFilePaths.forEach(path => {
          wx.uploadFile({
            url: app.globalData.baseUrl + '/api/gpx/image/add/img',
            filePath: path,
            name: 'file',
            success: uploadRes => {
              const resObj = JSON.parse(uploadRes.data);
              if (resObj.code === 200 && resObj.data) {
                const filename = resObj.data.filename;
                const url = filename.startsWith('http') ? filename : `${app.globalData.baseUrl}/uploads/img/${filename}`;
                const uploadTime = new Date().toISOString();
                const newImg = { url, filename, uploadTime, remark: '', globalIndex: this.data.images.length };
                const images = [...this.data.images, newImg];
                this.groupImages(images);
              }
            }
          });
        });
      }
    });
  },
  // 删除图片
  deleteImage(e) {
    const idx = e.currentTarget.dataset.index;
    const images = [...this.data.images];
    images.splice(idx, 1);
    // 重新分配globalIndex
    images.forEach((img, i) => img.globalIndex = i);
    this.groupImages(images);
  },
  // 编辑图片描述
  editImage(e) {
    const idx = e.currentTarget.dataset.index;
    const images = this.data.images;
    wx.showModal({
      title: '编辑描述',
      editable: true,
      placeholderText: '请输入描述',
      success: res => {
        if (res.confirm && res.content) {
          images[idx].remark = res.content;
          this.groupImages(images);
        }
      }
    });
  },
  // 预览图片
  previewImage(e) {
    const index = e.currentTarget.dataset.index;
    const urls = this.data.images.map(img => img.url);
    wx.previewImage({
      current: urls[index],
      urls
    });
  },
  // 确认保存
  confirmInfo() {
    wx.request({
      url: app.globalData.baseUrl + '/api/gpx/info',
      method: 'POST',
      data: this.data.gpxInfo,
      header: { 'content-type': 'application/json' },
      success: res => {
        if (res.data && res.data.code === 200) {
          const gpxId = res.data.data.id || res.data.data.gpxId;
          const imageList = this.data.images.map(img => ({
            gpxId,
            url: img.url,
            filename: img.filename,
            uploadTime: img.uploadTime,
            remark: img.remark || ''
          }));
          if (imageList.length > 0) {
            wx.request({
              url: app.globalData.baseUrl + '/api/gpx/image/addBatch',
              method: 'POST',
              data: imageList,
              header: { 'content-type': 'application/json' },
              success: imgRes => {
                wx.showToast({ title: '已保存', icon: 'success' });
                wx.navigateBack();
              }
            });
          } else {
            wx.showToast({ title: '已保存', icon: 'success' });
            wx.navigateBack();
          }
        }
      }
    });
  },
  cancelInfo() {
    wx.navigateBack();
  },
  onMarkerTap(e) {
    const markerId = e.markerId;
    const marker = this.data.markers.find(m => m.id === markerId);
    if (marker && this.mapCtx) {
      this.mapCtx.moveToLocation({
        longitude: marker.longitude,
        latitude: marker.latitude
      });
    }
  },
  tapLegendStart() {
    if (this.data.markers && this.data.markers.length > 0 && this.mapCtx) {
      const marker = this.data.markers[0];
      this.mapCtx.moveToLocation({
        longitude: marker.longitude,
        latitude: marker.latitude
      });
    }
  },
  tapLegendEnd() {
    if (this.data.markers && this.data.markers.length > 1 && this.mapCtx) {
      const marker = this.data.markers[1];
      this.mapCtx.moveToLocation({
        longitude: marker.longitude,
        latitude: marker.latitude
      });
    }
  },
  // 移除 loadImages 方法
  // 移除 chooseImage 方法
});

// 轨迹点解析
function parseGpxPoints(gpxStr) {
  const reg = /<trkpt[^>]*lat="([\d\.\-]+)"[^>]*lon="([\d\.\-]+)"[^>]*>/g;
  let match, points = [];
  while ((match = reg.exec(gpxStr)) !== null) {
    points.push({
      latitude: parseFloat(match[1]),
      longitude: parseFloat(match[2])
    });
  }
  return points;
}
// 解析distance、startTime、endTime等（可根据gpx内容自定义实现）
function parseGpxRoadName(gpxStr) {
  const match = gpxStr.match(/<name>([^<]+)<\/name>/);
  return match ? match[1] : '';
}
function parseGpxDistance(gpxStr) {
  // 支持<distance>xxx</distance>或<extensions><distance>xxx</distance></extensions>
  const match = gpxStr.match(/<distance>([\d\.]+)<\/distance>/);
  return match ? match[1] : '';
}
function parseGpxStartTime(gpxStr) {
  const match = gpxStr.match(/<time>([^<]+)<\/time>/);
  return match ? match[1] : '';
}
function parseGpxEndTime(gpxStr) {
  const times = [...gpxStr.matchAll(/<time>([^<]+)<\/time>/g)];
  return times.length ? times[times.length-1][1] : '';
}